'use client'

import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  IconActivity,
  IconChartBar,
  IconTrendingUp,
  IconTrendingDown,
  IconDownload,
  IconEye,
  IconSettings,
  IconFileText,
  IconTarget,
  IconCheck,
  IconX,
  IconAlertTriangle
} from "@tabler/icons-react"

export default function OptimizationPage() {
  const [selectedScenario, setSelectedScenario] = useState('scenario1')
  const [selectedMetric, setSelectedMetric] = useState('efficiency')

  // 模拟优化方案数据
  const optimizationScenarios = [
    {
      id: 'scenario1',
      name: '方案A：传统布局',
      description: '当前医院布局，无优化调整',
      metrics: {
        efficiency: 65,
        waitingTime: 45,
        resourceUtilization: 72,
        patientSatisfaction: 78,
        cost: 85
      },
      status: 'baseline',
      createdAt: '2025-01-15',
      author: '系统管理员'
    },
    {
      id: 'scenario2',
      name: '方案B：智能分流',
      description: '基于AI的智能患者分流和路径优化',
      metrics: {
        efficiency: 82,
        waitingTime: 28,
        resourceUtilization: 88,
        patientSatisfaction: 92,
        cost: 75
      },
      status: 'optimized',
      createdAt: '2025-01-15',
      author: '张译文'
    },
    {
      id: 'scenario3',
      name: '方案C：资源重组',
      description: '科室资源重新配置和空间优化',
      metrics: {
        efficiency: 78,
        waitingTime: 32,
        resourceUtilization: 85,
        patientSatisfaction: 85,
        cost: 70
      },
      status: 'optimized',
      createdAt: '2025-01-15',
      author: '张译文'
    },
    {
      id: 'scenario4',
      name: '方案D：综合优化',
      description: '多目标优化：效率、成本、满意度平衡',
      metrics: {
        efficiency: 88,
        waitingTime: 25,
        resourceUtilization: 92,
        patientSatisfaction: 95,
        cost: 68
      },
      status: 'recommended',
      createdAt: '2025-01-15',
      author: '张译文'
    }
  ]

  const metrics = {
    efficiency: { name: '运营效率', unit: '%', better: 'higher' },
    waitingTime: { name: '平均等待时间', unit: '分钟', better: 'lower' },
    resourceUtilization: { name: '资源利用率', unit: '%', better: 'higher' },
    patientSatisfaction: { name: '患者满意度', unit: '%', better: 'higher' },
    cost: { name: '运营成本', unit: '万元/月', better: 'lower' }
  }

  const getMetricColor = (metric: string, value: number) => {
    const metricConfig = metrics[metric as keyof typeof metrics]
    if (!metricConfig) return 'text-gray-600'

    if (metricConfig.better === 'higher') {
      return value >= 80 ? 'text-green-600' : value >= 60 ? 'text-yellow-600' : 'text-red-600'
    } else {
      return value <= 30 ? 'text-green-600' : value <= 50 ? 'text-yellow-600' : 'text-red-600'
    }
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'baseline':
        return <Badge variant="outline">基准方案</Badge>
      case 'optimized':
        return <Badge variant="secondary">优化方案</Badge>
      case 'recommended':
        return <Badge variant="default">推荐方案</Badge>
      default:
        return <Badge variant="outline">{status}</Badge>
    }
  }

  const handleExportJSON = () => {
    const payload = {
      generatedAt: new Date().toISOString(),
      selectedScenario,
      selectedMetric,
      scenarios: optimizationScenarios
    }
    const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'optimization_report.json'
    a.click()
    URL.revokeObjectURL(url)
  }

  const handleExportPDF = () => {
    const selected = optimizationScenarios.find(s => s.id === selectedScenario) || optimizationScenarios[0]
    const lines = [
      '# 医疗空间优化报告 (Mock)',
      `生成时间: ${new Date().toLocaleString()}`,
      `当前方案: ${selected.name}`,
      '指标摘要:',
      `- 运营效率: ${selected.metrics.efficiency}%`,
      `- 平均等待: ${selected.metrics.waitingTime} 分钟`,
      `- 资源利用: ${selected.metrics.resourceUtilization}%`,
      `- 满意度: ${selected.metrics.patientSatisfaction}%`,
      `- 成本: ${selected.metrics.cost} 万元/月`,
      '',
      '说明: 本PDF为演示用途，非真实渲染。'
    ].join('\n')
    const blob = new Blob([lines], { type: 'application/pdf' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'optimization_report.pdf'
    a.click()
    URL.revokeObjectURL(url)
  }

  return (
    <div className="min-h-screen gradient-bg p-6">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100 mb-2">优化方案对比</h1>
        <p className="text-gray-600 dark:text-gray-400">多目标优化与约束校验，方案推荐与报告生成</p>
      </div>

      {/* 优化概览卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <Card className="glass-card modern-shadow-hover">
          <CardContent className="p-4 text-center">
            <IconTarget className="w-8 h-8 text-blue-600 mx-auto mb-2" />
            <div className="text-2xl font-bold text-blue-600 dark:text-blue-400">4</div>
            <div className="text-sm text-blue-600 dark:text-blue-400">优化方案</div>
          </CardContent>
        </Card>
        <Card className="glass-card modern-shadow-hover">
          <CardContent className="p-4 text-center">
            <IconTrendingUp className="w-8 h-8 text-green-600 mx-auto mb-2" />
            <div className="text-2xl font-bold text-green-600 dark:text-green-400">23%</div>
            <div className="text-sm text-green-600 dark:text-green-400">效率提升</div>
          </CardContent>
        </Card>
        <Card className="glass-card modern-shadow-hover">
          <CardContent className="p-4 text-center">
            <IconTrendingDown className="w-8 h-8 text-purple-600 mx-auto mb-2" />
            <div className="text-2xl font-bold text-purple-600 dark:text-purple-400">44%</div>
            <div className="text-sm text-purple-600 dark:text-purple-400">等待时间减少</div>
          </CardContent>
        </Card>
        <Card className="glass-card modern-shadow-hover">
          <CardContent className="p-4 text-center">
            <IconCheck className="w-8 h-8 text-orange-600 mx-auto mb-2" />
            <div className="text-2xl font-bold text-orange-600 dark:text-orange-400">17%</div>
            <div className="text-sm text-orange-600 dark:text-orange-400">成本节约</div>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：方案列表 */}
        <div className="lg:col-span-1">
          <Card className="border border-gray-200">
            <CardHeader>
              <CardTitle className="text-lg">优化方案</CardTitle>
              <CardDescription>选择方案进行详细对比</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {optimizationScenarios.map((scenario) => (
                  <div
                    key={scenario.id}
                    className={`p-4 border rounded-lg cursor-pointer transition-colors ${selectedScenario === scenario.id
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-gray-200 hover:border-gray-300'
                      }`}
                    onClick={() => setSelectedScenario(scenario.id)}
                  >
                    <div className="flex items-center justify-between mb-2">
                      <h3 className="font-medium text-gray-900">{scenario.name}</h3>
                      {getStatusBadge(scenario.status)}
                    </div>
                    <p className="text-sm text-gray-600 mb-3">{scenario.description}</p>
                    <div className="flex items-center justify-between text-xs text-gray-500">
                      <span>创建者: {scenario.author}</span>
                      <span>{scenario.createdAt}</span>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 右侧：方案详情和对比 */}
        <div className="lg:col-span-2">
          <Tabs value={selectedMetric} onValueChange={setSelectedMetric} className="w-full">
            <TabsList className="grid w-full grid-cols-5">
              <TabsTrigger value="efficiency">效率</TabsTrigger>
              <TabsTrigger value="waitingTime">等待时间</TabsTrigger>
              <TabsTrigger value="resourceUtilization">资源利用</TabsTrigger>
              <TabsTrigger value="patientSatisfaction">满意度</TabsTrigger>
              <TabsTrigger value="cost">成本</TabsTrigger>
            </TabsList>

            <TabsContent value={selectedMetric} className="space-y-4">
              {/* 指标对比图表 */}
              <Card className="border border-gray-200">
                <CardHeader>
                  <CardTitle className="text-lg">
                    {metrics[selectedMetric as keyof typeof metrics]?.name} 对比
                  </CardTitle>
                  <CardDescription>各方案在该指标上的表现</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {optimizationScenarios.map((scenario) => {
                      const value = scenario.metrics[selectedMetric as keyof typeof scenario.metrics]
                      const metricConfig = metrics[selectedMetric as keyof typeof metrics]
                      const isBetter = metricConfig?.better === 'higher' ? value >= 80 : value <= 30

                      return (
                        <div key={scenario.id} className="flex items-center space-x-4">
                          <div className="w-32">
                            <span className="text-sm font-medium">{scenario.name}</span>
                          </div>
                          <div className="flex-1">
                            <div className="flex items-center space-x-2">
                              <div className="flex-1 bg-gray-200 rounded-full h-3">
                                <div
                                  className={`h-3 rounded-full ${isBetter ? 'bg-green-500' : 'bg-blue-500'
                                    }`}
                                  style={{ width: `${Math.min(value, 100)}%` }}
                                ></div>
                              </div>
                              <span className={`text-sm font-medium w-16 ${getMetricColor(selectedMetric, value)}`}>
                                {value}{metricConfig?.unit}
                              </span>
                            </div>
                          </div>
                          {scenario.status === 'recommended' && (
                            <IconCheck className="w-5 h-5 text-green-500" />
                          )}
                        </div>
                      )
                    })}
                  </div>
                </CardContent>
              </Card>

              {/* 约束校验结果 */}
              <Card className="border border-gray-200">
                <CardHeader>
                  <CardTitle className="text-lg">约束校验结果</CardTitle>
                  <CardDescription>方案可行性验证</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {[
                      { constraint: "消防通道要求", status: "通过", description: "所有方案满足消防通道宽度要求" },
                      { constraint: "感染控制隔离", status: "通过", description: "感染科隔离区域配置合理" },
                      { constraint: "无障碍设施", status: "通过", description: "无障碍通道和设施配置完整" },
                      { constraint: "设备间距", status: "通过", description: "医疗设备间距符合安全标准" },
                      { constraint: "人员密度", status: "警告", description: "方案D在高峰时段可能超出人员密度限制" }
                    ].map((item, index) => (
                      <div key={index} className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <div className={`w-3 h-3 rounded-full ${item.status === '通过' ? 'bg-green-500' : 'bg-yellow-500'
                          }`}></div>
                        <div className="flex-1">
                          <div className="flex items-center space-x-2">
                            <span className="font-medium">{item.constraint}</span>
                            <Badge variant={item.status === '通过' ? 'default' : 'secondary'}>
                              {item.status}
                            </Badge>
                          </div>
                          <p className="text-sm text-gray-600">{item.description}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* 推荐方案详情 */}
              <Card className="border border-green-200 bg-green-50">
                <CardHeader>
                  <CardTitle className="text-lg text-green-800">推荐方案：方案D - 综合优化</CardTitle>
                  <CardDescription className="text-green-700">
                    基于多目标优化算法，平衡效率、成本、满意度等多个指标
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <h4 className="font-medium text-green-800 mb-2">主要优势</h4>
                      <ul className="space-y-1 text-sm text-green-700">
                        <li>• 运营效率提升 23%</li>
                        <li>• 等待时间减少 44%</li>
                        <li>• 资源利用率提升 20%</li>
                        <li>• 患者满意度提升 17%</li>
                        <li>• 运营成本节约 17%</li>
                      </ul>
                    </div>
                    <div>
                      <h4 className="font-medium text-green-800 mb-2">实施建议</h4>
                      <ul className="space-y-1 text-sm text-green-700">
                        <li>• 分阶段实施，先试点后推广</li>
                        <li>• 重点关注人员密度控制</li>
                        <li>• 加强员工培训和流程优化</li>
                        <li>• 建立效果监测和反馈机制</li>
                      </ul>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>

          {/* 操作按钮 */}
          <div className="flex space-x-3 mt-6">
            <Button className="flex items-center space-x-2" onClick={handleExportPDF}>
              <IconDownload className="w-4 h-4" />
              <span>导出报告 (PDF)</span>
            </Button>
            <Button variant="outline" className="flex items-center space-x-2" onClick={handleExportJSON}>
              <IconFileText className="w-4 h-4" />
              <span>导出数据 (JSON)</span>
            </Button>
            <Button variant="outline" className="flex items-center space-x-2">
              <IconSettings className="w-4 h-4" />
              <span>配置约束</span>
            </Button>
            <Button variant="outline" className="flex items-center space-x-2">
              <IconEye className="w-4 h-4" />
              <span>3D预览</span>
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
